<?php


namespace app\api\model;


use EasyWeChat\Foundation\Application;
use think\Cache;
use Yansongda\Pay\Pay;

class Wechat
{
    private $appid;
    private $secret;
    private $accessTokenUrl;
    private $authUrl;
    private $wechatPay;

    public function __construct($code = null)
    {
        $this->appid = config('wechat.app_id');
        $this->secret = config('wechat.app_secret');
        $this->accessTokenUrl = sprintf(config('wechat.access_token_url'), $this->appid, $this->secret);
        $this->authUrl = sprintf(config('wechat.auth_url'), $this->appid, $this->secret, $code);
        $this->wechatPay = Pay::wechat(config('wechat'));
    }

    /**
     * 小程序授权
     * @return array
     */
    public function getAuth($token = 'session_key')
    {
        $result = curl_get($this->authUrl);
        if (isset($result['errcode']) && $result['errcode']) {
            return ['errcode' => $result['errcode'], 'errmsg' => $result['errmsg']];
        }
        //缓存session_key
        Cache::set($token, $result['session_key'], 0);
        return ['errcode' => 0, 'openid' => $result['openid']];
    }

    /**
     * 获取调用凭证
     * @return array
     */
    public function getAccessToken()
    {
        $access_token = Cache::get('access_token');
        if (!$access_token) {
            $result = curl_get($this->accessTokenUrl);
            if (isset($result['errcode']) && $result['errcode'] !== 0) {
                return ['errcode' => $result['errcode'], 'errmsg' => $result['errmsg']];
            }
            //缓存access_token
            Cache::set('access_token', $result['access_token'], $result['expires_in']);
            $access_token = $result['access_token'];
        }
        return $access_token;
    }

    /**
     * 小程序码
     * @return mixed
     */
    public function getORCode($data)
    {
        $access_token = $this->getAccessToken();
        if (isset($access_token['errcode'])) {
            return $access_token;
        }
        $params = [
            'scene' => $data['scene'] ?? 'chase',
            'page' => $data['page'] ?? '',
            'width' => $data['width'] ?? 430,
            'auto_color' => boolval($data['auto_color'] ?? false),
            'line_color' => $data['line_color'] ?? ['r'=> 0, 'g' => 0, 'b' => 0],
            'is_hyaline' => boolval($data['is_hyaline'] ?? false)
        ];

        $result = curl_post(sprintf(config('wechat.or_code'), $access_token), $params);
        if (isset($result['errcode']) && $result['errcode'] !== 0) {
            return ['errcode' => $result['errcode'], 'errmsg' => $result['errmsg']];
        }
        return $result;
    }

    /**
     * 订阅消息
     */
    public function sendSubscribeMessage($order, $page)
    {
        $access_token = $this->getAccessToken();
        if (isset($access_token['errcode'])) {
            return $access_token;
        }
        $params = [
            'touser' => $order->user->openid,
            'template_id' => config('wechat.template_id'),
            'page' => $page ?: '',
            'data' => [
                'thing10' => [
                    'value' => '拾玖造型19HairSalon'
                ],
                'name2' => [
                    'value' => $order->design->nickname
                ],
                'thing1' => [
                    'value' => $order->design_service->service->service_name
                ],
                'amount8' => [
                    'value' => $order->user->money
                ],
                'character_string4' => [
                    'value' => $order->order_no
                ]
            ]
        ];
        $result = curl_post(sprintf(config('wechat.send_subscribe_message_url'), $access_token), $params);
        $result = json_decode($result, true);
        if (isset($result['errcode']) && $result['errcode'] !== 0) {
            return ['errcode' => $result['errcode'], 'errmsg' => $result['errmsg']];
        }
        return ['errcode' => 0, 'errmsg' => 'ok'];
    }

    /**
     * 统一下单
     */
    public function miniapp($order, $openid, $notify_url)
    {
        return $this->wechatPay->miniapp([
            'openid' => $openid,
            'out_trade_no' => $order['order_no'],
            'total_fee' => $order['total_amount'] * 100,
            'body' => config('wechat.body'),
            'notify_url' => $notify_url
        ]);
    }

    public function wechatPay()
    {
        return $this->wechatPay;
    }

    /**
     * 查询支付结果
     */
    public function find($order_no)
    {
        return $this->wechatPay->find($order_no);
    }

    /**
     *
     */
    public function verify()
    {
        return $this->wechatPay->verify();
    }
}